import {
  behavior as computedBehavior
} from "miniprogram-computed";

Component({
  behaviors: [computedBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    list: {
      type: Array,
      value: []
    }
  },

  watch: {
    list: function (v) {
      this.setData({
        teamList: JSON.parse(JSON.stringify(v))
      })
    }
  },

  lifetimes: {
    attached() {
      this.setData({
        teamList: JSON.parse(JSON.stringify(this.properties.list))
      })
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    teamList: []
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleClickClose() {
      this.triggerEvent("onClose");

      setTimeout(() => {
        this.setData({
          teamList: JSON.parse(JSON.stringify(this.properties.list))
        })
      }, 300)
    },

    handleClickConfirm() {
      this.triggerEvent("onConfirm", this.data.teamList);
    },

    handleSelect(e) {
      let item = e.currentTarget.dataset;
      let index = item.index;
      if (item.id == 0) {
        if (this.data.teamList[0].checked) {
          this.data.teamList.forEach(item => {
            item.checked = false
          })
        } else {
          this.data.teamList.forEach(item => {
            item.checked = true
          })
        }
      } else {
        this.data.teamList[index].checked = !this.data.teamList[index].checked
        let count = 0;
        this.data.teamList.forEach(item => {
          if (item.checked && item.fUserId != 0) {
            count++;
          }
        })
        if (this.data.teamList.length - 1 != count) {
          this.data.teamList[0].checked = false
        } else {
          this.data.teamList[0].checked = true
        }
      }
      this.setData({
        teamList: this.data.teamList
      })
    }
  }
})